# admin_views.py
from flask import Blueprint, render_template, redirect, url_for, flash, abort, current_app
from flask_login import login_required, current_user
from models import User, Photo, db
from forms import PhotoForm
from functools import wraps

admin = Blueprint('admin', __name__, url_prefix='/admin')

# 管理员权限检查装饰器
def admin_required(func):
    @wraps(func)
    def decorated_view(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin:
            abort(403)
        return func(*args, **kwargs)
    return decorated_view

# 管理员仪表盘
@admin.route('/dashboard')
@admin_required
def dashboard():
    # 统计信息
    total_users = User.query.count()
    total_photos = Photo.query.count()
    pending_photos = Photo.query.filter_by(approved=False).count()
    
    # 最新上传
    latest_photos = Photo.query.order_by(Photo.created_at.desc()).limit(5).all()
    
    # 最新注册用户
    latest_users = User.query.order_by(User.created_at.desc()).limit(5).all()
    
    return render_template('admin/dashboard.html', 
                           total_users=total_users,
                           total_photos=total_photos,
                           pending_photos=pending_photos,
                           latest_photos=latest_photos,
                           latest_users=latest_users)

# 作品管理
@admin.route('/photos')
@admin_required
def manage_photos():
    # 获取所有待审作品
    pending_photos = Photo.query.filter_by(approved=False).all()
    
    # 获取所有已批准作品
    approved_photos = Photo.query.filter_by(approved=True).all()
    
    return render_template('admin/photos.html', 
                           pending_photos=pending_photos,
                           approved_photos=approved_photos)

# 批准作品
@admin.route('/approve/<int:photo_id>')
@admin_required
def approve_photo(photo_id):
    photo = Photo.query.get_or_404(photo_id)
    photo.approved = True
    db.session.commit()
    
    flash(f'作品 "{photo.title}" 已批准', 'success')
    return redirect(url_for('admin.manage_photos'))

# 拒绝作品
@admin.route('/reject/<int:photo_id>')
@admin_required
def reject_photo(photo_id):
    photo = Photo.query.get_or_404(photo_id)
    db.session.delete(photo)
    db.session.commit()
    
    flash(f'作品 "{photo.title}" 已拒绝', 'warning')
    return redirect(url_for('admin.manage_photos'))